package com.e3.sysmg.security.client;

import com.e3.sysmg.security.model.UserModel;
import com.e3.web.core.client.EditorListener;
import com.e3.web.core.client.GXTHelper;
import com.e3.web.core.client.GwtAsyncCallback;
import com.e3.web.core.client.ListenerManager;
import com.e3.web.widget.client.MyDialog;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.user.client.Element;

public class UserEditorDialog extends MyDialog{
	
	private UserMessages MESSAGES = UserMessages.INSTANCE;
	
	private UserRPCServiceAsync service = UserRPCService.Util.getInstance();
	
	private UserFormPanel formPanel;
	
	private boolean isNew = true;
	
	private ListenerManager<UserModel> listenerManager = new ListenerManager<UserModel>();
	
	@Override
	protected void onRender(Element parent, int index) {
		super.onRender(parent, index);
		setLayout(new FitLayout());
		setSize(600,500);
		
		add(getUserFormPanel());
	}
	
	public void addEditorListeners(EditorListener<UserModel> listener){
		listenerManager.addEditorListener(listener);
	}
	
	public UserFormPanel getUserFormPanel(){
		if(formPanel == null){
			formPanel = new UserFormPanel();
		}
		return formPanel;
	}

	public void showDialog(UserModel userModel,boolean isNew){
		this.isNew = isNew;
		if(isNew){
			this.setHeading(MESSAGES.title_new(MESSAGES.local_name()));
		}
		else{
			this.setHeading(MESSAGES.title_modify(userModel.getName()));
		}
		getUserFormPanel().setFormValue(userModel);
		this.setVisible(true);
	}

	@Override
	protected void onOk() {
		UserModel model = getUserFormPanel().getFormValue();
		if(model == null){
			return;
		}
		
		String code = model.getCode();
		if(code==null||code.trim().length()==0){
			MessageBox.alert(MESSAGES.msgbox_alert_title(), MESSAGES.msg_notnull(UserHelper.INSTANCE.getFieldDisplayName(UserModel.CODE)), null);
			return;
		}
		
		String password = model.getPassword();
		if(password==null||password.trim().length()==0){
			MessageBox.alert(MESSAGES.msgbox_alert_title(), MESSAGES.msg_notnull(UserHelper.INSTANCE.getFieldDisplayName(UserModel.PASSWORD)), null);
			return;
		}
		
		GXTHelper.maskSave(this);
		if(isNew){
			newUser(model);
		}
		else{
			modifyUser(model);
		}
	}
	
	private void modifyUser(final UserModel model) {
		service.modifyUser(model, new GwtAsyncCallback<UserModel>(this) {
			@Override
			public void doSuccess(UserModel result) {
				listenerManager.notifyEditorSuccess(result);
				setVisible(false);
			}
		});
	}

	private void newUser(final UserModel userModel) {
		service.newUser(userModel, new GwtAsyncCallback<UserModel>(this) {
			@Override
			public void doSuccess(UserModel result) {
				listenerManager.notifyEditorSuccess(result);
				setVisible(false);
			}
		});
	}
}
